package com.zy.garbage.util;


import com.google.gson.Gson;
import com.mzlion.easyokhttp.HttpClient;
import com.zy.garbage.exception.CommonException;
import lombok.Data;

public class HttpUtil {

    public static Object getObjectFromJson(String jsonString, Class<?> clazz){
        return new Gson().fromJson(jsonString, clazz);
    }
    @Data
    public class WRes{
        private String openid;
        private String session_key;
    }
    public static WRes sessionKey(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx156cc69fadc9380b&secret=bd204e94b46b5982be140a4ce8a63dd9&grant_type=authorization_code&js_code="+code;
        String responseData = HttpClient
                // 请求方式和请求url
                .get(url)
                .asString();
//        String responseData = "{\"session_key\":\"bwTODbPdBDEawiwzBzevJw==\",\"openid\":\"oMHrL5Spi2L8Y2Z_vp2iDm-FbxTA\"}";
        WRes res = (WRes) getObjectFromJson(responseData,WRes.class);
        if (res.getOpenid()==null||res.session_key==null){
            throw new CommonException(500,"获取code值失败");
        }
        return res;
    }
    public static void main(String[] args) {
        try {
//            Map<String, Object> map = sessionKey("003oooll2KoZr64eA0ol2IXdHk3ooolI");
            WRes wRes = sessionKey("0432YxFa1y5wrA0GL7Ja1AskRR12YxFj");
            System.out.println(wRes.getOpenid());
            System.out.println(wRes.getSession_key());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
